package me.buick.util.jmeter.snmpprocess.snmpmgmt;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import me.buick.util.snmp.core.AbstractPerfDAOFactory;
import me.buick.util.snmp.core.SupportedOS;
import me.buick.util.snmp.core.SupportedProtocol;
import me.buick.util.snmp.core.dao.ProcessInfoDAO;
import me.buick.util.snmp.core.pojo.ProcessInfoPojo;

/**
 * 
 * Version 1.0
 * 
 * This class is used to be a communication adaptor between SNMPProcessSampler and Buick SNMP Utility API.
 * Every SNMPProcessSampler thread has their own SNMPProcessDataAdaptor instance until this Sampler is shut down.
 * 
 * @author buick
 *
 */

public class SNMPProcessDataAdaptor {
	
	String  server;
	int     port     = 161;
	int     interval = 1500;
	boolean	flag = false;
	
	private AbstractPerfDAOFactory snmpDAOFactory = null;
	private ProcessInfoDAO procInfoDAO = null;
	
	public SNMPProcessDataAdaptor(String server, int port, SupportedOS os,int snmpDataRetriveInterval) {
		this.interval = snmpDataRetriveInterval;
		snmpDAOFactory = AbstractPerfDAOFactory.getPerfDAOFactory(os, SupportedProtocol.SNMP, server, port, snmpDataRetriveInterval);
		procInfoDAO    = snmpDAOFactory.getProcessInfoDAO();
	}
	
	protected void finalize() throws Throwable {
		  super.finalize();
		  if(this.snmpDAOFactory != null){
			  this.snmpDAOFactory.discardDAOs();
		  }
		}

	public void fillSampleResult(SNMPProcessSampleResult sampleResult){
			
		sampleResult.setTimeStamp(System.currentTimeMillis());
		
		List<ProcessInfoPojo> procInfoPojoList = procInfoDAO.getProcessInfo(sampleResult.getProcDescr());
		
		if(!flag){
			flag = true;
			try {
				Thread.sleep(Long.parseLong(sampleResult.getSnmpDataRetriveInterval()));
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		
//		long totalMEMUsageKBytes = 0;
//			
//		double totalCPUUsagePerc = 0.00;
		
		Map<Integer, ProcessInfoPojo> currentProcesses = new HashMap<Integer, ProcessInfoPojo>();
			
		if(procInfoPojoList != null && procInfoPojoList.size() > 0){
			for(ProcessInfoPojo ppojo : procInfoPojoList){
//				totalMEMUsageKBytes += ppojo.getProcPerfMemKBytes();
//				totalCPUUsagePerc   += ppojo.getCPUPerc();
				currentProcesses.put(ppojo.getPid(), ppojo);
			}
		}
			
		sampleResult.setProcessPojoMap(currentProcesses);
//		double cpuPerc = totalCPUUsagePerc;
//		if(cpuPerc >= 1){
//			cpuPerc = 1.00;
//		}
//		sampleResult.setTotalCPUPerc(cpuPerc);
//		sampleResult.setTotalMemUsage(totalMEMUsageKBytes);
		sampleResult.setSnmpSuiteID(sampleResult.getSnmpSuiteID());
	}
	
	public void discardDAOs(){
		if(this.snmpDAOFactory != null){
			snmpDAOFactory.discardDAOs();
		}
	}
	
}
